package com.an.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 *
 * @ClassName: WebSocketChatServer
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author antch,861710865@qq.com
 * @date 2017年7月21日 下午2:27:56
 *
 */
public class WebSocketChatServer {

	private int port;

	public WebSocketChatServer(int port) {
		super();
		this.port = port;
	}

	public void run() {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup);
			b.channel(NioServerSocketChannel.class);
			b.childHandler(new WebSocketChatServerInitializer());
			b.option(ChannelOption.SO_BACKLOG, 128);
			b.childOption(ChannelOption.SO_KEEPALIVE, true);

			System.out.println("****" + "服务器启动开始" + "****");

			// 绑定端口，开始接收进来的连接
			ChannelFuture f = b.bind(port).sync();

			// 等待服务器 socket关闭
			//
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			System.err.println("启动失败");
			e.printStackTrace();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
			System.out.println("WebSocketChatServer 关闭了");
		}
	}

	public static void main(String[] args) {
		new WebSocketChatServer(8081).run();
	}
}
